package com.ruoyi.web.controller.shop.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.OrderConstants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.DO.order.ShopCreditOrderDO;
import com.ruoyi.common.entity.DO.shop.ShopAppletDO;
import com.ruoyi.common.entity.VO.RefundVO;
import com.ruoyi.common.entity.VO.order.*;
import com.ruoyi.common.entity.VO.shop.ShopProductSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopProductVO;
import com.ruoyi.common.entity.wxpay.WXPay;
import com.ruoyi.common.entity.wxpay.WXPayConstants;
import com.ruoyi.common.entity.wxpay.WxConfig;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.quartz.task.RyTask;
import com.ruoyi.system.mapper.IBackShopConfigMapper;
import com.ruoyi.web.controller.member.mapper.IBackMemberMapper;
import com.ruoyi.web.controller.order.service.IBackOrderService;
import com.ruoyi.web.controller.shop.service.IBackShopAppletService;
import com.ruoyi.web.controller.shop.service.IBackShopProductService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 站点-订单管理
 */
@Controller
@RequestMapping("/back/shopOrder")
public class BackShopOrderController extends BaseController {
    private String prefix = "shop/order";

    @Resource
    private IBackOrderService orderService;

    @Resource
    private IBackShopConfigMapper configMapper;

    @Resource
    private IBackMemberMapper memberMapper;

    @Resource
    private IBackShopProductService backShopProductService;

    @Resource
    private BackShopOrderRefundController backShopOrderRefundController;

    /**
     * 页面-充值订单列表
     *
     * @return
     */
    @RequiresPermissions("back:shopOrder:rechargeList")
    @GetMapping("/rechargeList")
    public String rechargeList() {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        return prefix + "/rechargeList";
    }

    /**
     * 页面-加油订单列表
     *
     * @return
     */
    @RequiresPermissions("back:shopOrder:petrolList")
    @GetMapping("/petrolList")
    public String petrolList(ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setShopId(ShiroUtils.getShopId());
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
        List<ShopProductVO> petrolList = backShopProductService.searchList(searchVO);
        petrolList.forEach(x -> x.setProductName(x.getProductCategory() + x.getProductName()));
        mmap.put("petrolTypeList", petrolList);
        mmap.put("productAttrList", backShopProductService.searchAttrList(searchVO));
        return prefix + "/petrolList";
    }

    /**
     * 页面-加油订单缩略列表
     *
     * @return
     */
    @RequiresPermissions("back:shopOrder:petrolList")
    @GetMapping("/petrolDescList/{productId}/{timeRange}")
    public String petrolDescList(@PathVariable("productId") Long productId, @PathVariable("timeRange") String timeRange, ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setProductId(productId);
        searchVO.setShopId(ShiroUtils.getShopId());
        mmap.put("productAttrList", backShopProductService.searchAttrList(searchVO));
        mmap.put("productId", productId);
        mmap.put("beginTime", timeRange.split(",")[0].replace("%20", " "));
        mmap.put("endTime", timeRange.split(",")[1].replace("%20", " "));
        return prefix + "/petrolDescList";
    }

    /**
     * 页面-充值订单缩略列表
     *
     * @return
     */
    @RequiresPermissions("back:shopOrder:rechargeDescList")
    @GetMapping("/rechargeDescList/{timeRange}")
    public String rechargeDescList(@PathVariable("timeRange") String timeRange, ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setShopId(ShiroUtils.getShopId());
        mmap.put("beginTime", timeRange.split(",")[0].replace("%20", " "));
        mmap.put("endTime", timeRange.split(",")[1].replace("%20", " "));
        return prefix + "/rechargeDescList";
    }

    /**
     * 页面-积分商城订单列表
     *
     * @return
     */
    @RequiresPermissions("back:shopOrder:creditList")
    @GetMapping("/creditList")
    public String creditList() {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        return prefix + "/creditList";
    }

    /**
     * 订单编辑-页面
     *
     * @return
     */
    @RequiresPermissions("back:shopOrder:edit")
    @GetMapping("edit/{orderSn}")
    public String edit(@PathVariable("orderSn") String orderSn, ModelMap mmap) {
        mmap.put("order", orderService.getDetailByOrderSn(orderSn));
        return prefix + "/edit";
    }

    /**
     * 页面-核销奖品
     *
     * @return
     */
    @GetMapping("creditExchange/{code}")
    public String creditExchange(@PathVariable("code") String code, ModelMap mmap) {
        ShopCreditOrderDO orderInfo = orderService.getDetailByExchangeCode(code);
        MemberDO memberInfo = memberMapper.selectByPrimaryKey(orderInfo.getMemberId());
        mmap.put("exchangeCode", code);
        mmap.put("createTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderInfo.getCreateTime()));
        if (1 == orderInfo.getOrderStatus()) {
            mmap.put("completeTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderInfo.getCompleteTime()));
        }
        mmap.put("info", orderInfo);
        mmap.put("memberPhone", memberInfo.getPhone());
        return prefix + "/creditExchange";
    }

    /**
     * 数据查询-充值订单列表（搜索）
     *
     * @param shopOrderSearchVO
     * @return
     */
    @RequiresPermissions("back:shopOrder:rechargeList")
    @PostMapping("/searchRechargeList")
    @ResponseBody
    public TableDataInfo searchRechargeList(ShopOrderSearchVO shopOrderSearchVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        shopOrderSearchVO.setShopId(ShiroUtils.getShopId());
        startPage();
        List<MemberRechargeOrderVO> list = orderService.searchRechargeList(shopOrderSearchVO);
        return getDataTable(list);
    }

    /**
     * 数据查询-加油订单列表（搜索）
     *
     * @param shopOrderSearchVO
     * @return
     */
    @RequiresPermissions("back:shopOrder:petrolList")
    @PostMapping("/searchPetrolList")
    @ResponseBody
    public TableDataInfo searchPetrolList(ShopOrderSearchVO shopOrderSearchVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        shopOrderSearchVO.setShopId(ShiroUtils.getShopId());
        startPage();
        List<ShopPetrolOrderVO> list = orderService.searchPetrolList(shopOrderSearchVO);
        return getDataTable(list);
    }

    /**
     * 数据查询-积分兑换订单列表（搜索）
     *
     * @param shopOrderSearchVO
     * @return
     */
    @RequiresPermissions("back:shopOrder:creditList")
    @PostMapping("/searchCreditList")
    @ResponseBody
    public TableDataInfo searchCreditList(ShopOrderSearchVO shopOrderSearchVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        shopOrderSearchVO.setShopId(ShiroUtils.getShopId());
        startPage();
        List<ShopCreditOrderVO> list = orderService.searchCreditList(shopOrderSearchVO);
        return getDataTable(list);
    }

    /**
     * 数据查询-积分兑换订单列表（搜索）
     *
     * @return
     */
//    @RequiresPermissions("back:shopOrder:wxInfo")
//    @GetMapping("/wxInfo")
//    @ResponseBody
//    public AjaxResult wxInfo() {
//        if (0 == ShiroUtils.getShopId()) {
//            throw new BusinessException("请先切换站点！");
//        }
//        ShopOrderSearchVO shopOrderSearchVO = new ShopOrderSearchVO();
//        shopOrderSearchVO.setShopId(ShiroUtils.getShopId());
//        shopOrderSearchVO.setOrderStatus(OrderConstants.OrderStatusEnum.COMPLETE.getValue());
//        shopOrderSearchVO.setPayStatus(OrderConstants.OrderPayStatusEnum.COMPLETE.getValue());
//        List<MemberRechargeOrderVO> list = orderService.searchRechargeList(shopOrderSearchVO);
//        ShopAppletDO shopApplet = backShopAppletService.getShopAppletInfoByShopId(shopOrderSearchVO.getShopId());
//        if (shopApplet == null || shopApplet.getIsEnable() == null || shopApplet.getIsDelete() == 1) {
//            throw new BusinessException("请重新开通该订单的商家小程序！");
//        }
//        if (shopApplet.getIsEnable() == 0) {
//            throw new BusinessException("请先上架该订单的商家小程序！");
//        }
//        WxConfig wxConfig = new WxConfig();
//        wxConfig.setAppID(shopApplet.getAppletAppId());
//        wxConfig.setKey(shopApplet.getAppletPayKey());
//        wxConfig.setMchID(shopApplet.getAppletMchId());
//        try {
//            wxConfig.setCertData(shopOrderSearchVO.getShopId());
//        } catch (Exception e) {
//            error("支付证书错误！");
//        }
//        WXPay wxpay = null;
//        try {
//            Map map = new LinkedHashMap<>();
//            wxpay = new WXPay(wxConfig);
//            for (MemberRechargeOrderVO one : list
//            ) {
//                map.clear();
//                map.put("out_trade_no", one.getPaySn());
//                Map<String, String> result = wxpay.orderQuery(map);
//                if(result.containsKey("trade_state") && result.get("trade_state").equals("REFUND")){
//                    System.out.println(one.getId()+":"+one.getOrderSn()+":"+one.getMemberId()+":"+one.getAmount());
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return AjaxResult.success();
//    }

    /**
     * 编辑订单-数据处理
     *
     * @param shopOrderVO
     * @return
     */
    @Log(title = "站点-订单管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("back:shopOrder:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(ShopOrderVO shopOrderVO) {
        if (ShiroUtils.getShopId() != 0) {
            //店铺修改订单信息
            shopOrderVO.setShopId(null);
            shopOrderVO.setMemberId(null);
            shopOrderVO.setOrderSn(null);
            shopOrderVO.setOrderBackSn(null);
            shopOrderVO.setPaySn(null);
            shopOrderVO.setProductCost(null);
            shopOrderVO.setOrderCost(null);
            shopOrderVO.setBuyCost(null);
            shopOrderVO.setOrderStatus(null);
            shopOrderVO.setPayStatus(null);
            shopOrderVO.setShopPayWay(null);
            shopOrderVO.setPayTime(null);
            shopOrderVO.setShopPayTime(null);
            shopOrderVO.setCreateTime(null);
            shopOrderVO.setRewardAmount(null);
            shopOrderVO.setRewardRate(null);
            shopOrderVO.setOrderBackSn(null);
            shopOrderVO.setShopPayStatus(null);
            shopOrderVO.setPayStatus(null);
            shopOrderVO.setExtraRemark(null);
            shopOrderVO.setIsEnable(null);
        }
        shopOrderVO.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        shopOrderVO.setUpdateTime(new Date());
        return toAjax(orderService.update(shopOrderVO));
    }

    /**
     * 页面跳转-订单导出
     *
     * @return
     */
    @RequiresPermissions("back:shopOrder:exportCustom")
    @GetMapping("/exportCustom")
    public String exportCustom() {
        return prefix + "/export";
    }

    /**
     * 数据处理-充值订单取消（未付款直接取消，已付款生成退款记录）
     */
    @Log(title = "站点-取消充值订单", businessType = BusinessType.OTHER)
    @RequiresPermissions("back:shopOrder:rechargeCancel")
    @PostMapping("/rechargeCancel")
    @ResponseBody
    public AjaxResult rechargeCancel(String orderSn) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        try {
            String refundSn = orderService.rechargeCancel(orderSn);
            try{
                backShopOrderRefundController.refundToMember(refundSn);
            }catch (Exception e){
                e.printStackTrace();
            }
        } catch (BusinessException e) {
            return error(e.getMessage());
        }
        return success("订单取消成功！如订单已支付会自动退款，请留意退款状态！");
    }

    /**
     * 数据处理-加油订单取消（未付款直接取消，已付款生成退款记录）
     */
    @Log(title = "站点-取消加油订单", businessType = BusinessType.OTHER)
    @RequiresPermissions("back:shopOrder:petrolCancel")
    @PostMapping("/petrolCancel")
    @ResponseBody
    public AjaxResult petrolCancel(String orderSn) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        try {
            String refundSn = orderService.petrolCancel(orderSn);
            try{
                backShopOrderRefundController.refundToMember(refundSn);
            }catch (Exception e){
                e.printStackTrace();
            }
        } catch (BusinessException e) {
            return error(e.getMessage());
        }
        return success("订单取消成功！如订单已支付会自动退款，请留意退款状态！");
    }

    /**
     * 核销奖品
     *
     * @return
     */
    @PostMapping("/creditExchange/{exchangeCode}")
    @ResponseBody
    public AjaxResult creditExchange(@PathVariable("exchangeCode") String exchangeCode, String password) {
        ShopCreditOrderDO orderInfo = orderService.getDetailByExchangeCode(exchangeCode);
        if (orderInfo == null) {
            return success("核销订单已无效！");
        }
        if (1 == orderInfo.getOrderStatus()) {
            return success("请勿重复核销！");
        }
        String truePassword = configMapper.searchValueByKey(SysConfigConstants.ShopConfigEnum.EXCHANGE_PASSWORD.getKey(), orderInfo.getShopId());
        if (StringUtils.isNotEmpty(truePassword)) {
            String md5TruePassword = Md5Utils.hash(truePassword);
            if (!md5TruePassword.equals(password)) {
                return error("核销密码输入错误！");
            }
        }
        try {
            orderService.handleCreditExchange(exchangeCode);
            return success("核销成功！");
        } catch (Exception e) {
            return error("核销失败！");
        }
    }


    /**
     * 数据处理-订单导出
     *
     * @return
     */
    @Log(title = "店铺-订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ShopOrderSearchVO shopOrderSearchVO) {
        if (StringUtils.isNotEmpty(shopOrderSearchVO.getOrderSnStr())) {
            if (shopOrderSearchVO.getOrderSnStr().contains(",")) {
                String[] orderSnArr = Convert.toStrArray(shopOrderSearchVO.getOrderSnStr());
                if (orderSnArr.length > 100) {
                    error("导出数据不能超过100条！");
                }
                shopOrderSearchVO.setOrderSnArr(orderSnArr);
            }
        }
        String sheetName = "";
        Map<String, Object> map = shopOrderSearchVO.getParams();
        if (map.containsKey("beginTime") && map.containsKey("endTime")) {
            sheetName += map.get("beginTime") + "到" + map.get("endTime") + "订单";
        } else if (map.containsKey("month")) {
            sheetName += map.containsKey("month") + "月份订单";
        } else {
            sheetName += "自定义导出订单";
        }
        shopOrderSearchVO.setShopId(ShiroUtils.getShopId());
        List<ShopOrderExportVO> orderList = orderService.searchShopOrderExportList(shopOrderSearchVO);
        ExcelUtil<ShopOrderExportVO> util = new ExcelUtil<>(ShopOrderExportVO.class);
        return util.exportExcel(orderList, sheetName);
    }

}
